package idv.arthur.work;

import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.gson.Gson;

/**
 * Servlet implementation class GetGroups
 */
//@WebServlet(description = "取得目前有的角色", urlPatterns = { "/GetGroups" })
public class GetGroups extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public GetGroups() {
        super();
    }

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		Widgets wid = new Widgets();
		Connection conn = null;
		PreparedStatement ps = null;
		ResultSet rs = null;
		String strSQL = "SELECT roleID, roleName FROM tms_role";
		String returnResult = "";
		ArrayList<Role> roles = new ArrayList<Role>();
		try {
			conn = wid.getConn(true);
			ps = conn.prepareStatement(strSQL);
			rs = ps.executeQuery();
			while (rs.next()) {
				Role role = new Role();
				role.setRoleID(rs.getInt("roleID"));
				role.setRoleName(rs.getString("roleName"));
				roles.add(role);
			}
		} catch (SQLException e) {
			returnResult = "{\"errorMsg\":\"" + wid.keepErrorMes(conn, ps, e, "", true) + "\"}";
		} finally {
			try {
				if (rs != null) {rs.close();}
				if (ps != null) {ps.close();}
				if (conn != null) {conn.close();}
			} catch (SQLException e) {
				returnResult = "{\"errorMsg\":\"" + e.toString() + "\"}";
			}
		}

		returnResult = new Gson().toJson(roles);
		returnResult = returnResult.substring(1, returnResult.length());
		returnResult = "{\"sqlData\":[" + returnResult + ",\"strSQL\":\""+ strSQL + "\",\"size\":\"" + roles.size()+ "\"}";

		response.setContentType("application/json");
		response.setCharacterEncoding("UTF-8");
		response.getWriter().write(returnResult);
	}
}

class Role {
	private int roleID;
	private String roleName;
	public int getRoleID() {
		return roleID;
	}
	public void setRoleID(int roleID) {
		this.roleID = roleID;
	}
	public String getRoleName() {
		return roleName;
	}
	public void setRoleName(String roleName) {
		this.roleName = roleName;
	}
	
}
